//
//  HJHTabBarController.swift
//  WeiBoPro
//
//  Created by nadyboy on 2018/4/26.
//  Copyright © 2018年 hjh. All rights reserved.
//

import UIKit

class HJHTabBarController: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setUpChiledVc()
        setUpStyle()
        setUpComoseBtn()
    }
    lazy var composeBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        btn.addTarget(self, action: #selector(composeBtnClick), for: .touchUpInside)
        return btn
    }()
    //设置屏幕方向 好处：需要横屏的时候单独处理
   override var supportedInterfaceOrientations: UIInterfaceOrientationMask
    {
    return .portrait
    }
    
    /**
     添加按钮方法
     */
   @objc private func composeBtnClick()
    {
    print("中间按钮点击额了-----")
    }
    
    /**
     设置样式
     */
    func setUpStyle(){
        
        tabBar.tintColor = UIColor.orange;
    }
  
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

//方法二 反射弧
extension HJHTabBarController
{
    //设置中间按钮
    public func setUpComoseBtn()
    {
    tabBar.addSubview(composeBtn)
    //中间按钮，偷懒方法
    let count = CGFloat(childViewControllers.count)
    let composerBtnWidth = tabBar.bounds.width/count - 1
    composeBtn.frame = tabBar.bounds.insetBy(dx: 2*composerBtnWidth, dy: 0)
    }
    //设置子控制器
    private func setUpChiledVc(){
        //判断是沙盒的还是网络的
        let dir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let dirPath = (dir as NSString).appendingPathComponent("main.json")
        var data = NSData(contentsOfFile: dirPath)
        
        if data == nil {
           //空的就加载本地的
            //1.获取路径
            let path =  Bundle.main.path(forResource: "main", ofType: "json")
            //2.获取data
            data = NSData(contentsOfFile: path!)
        }
        //3.转json数据
        guard let arr = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String : Any]] else {
            return
        }
        /*
        let arr:[[String : Any]] = [
            
            ["name":"HJHHomeViewController","title":"首页","image":"tabbar_home","vistor":["imageName":"","imageMsg":"关注一些人，回到这里看看有啥子惊喜"]
            ],
            
            ["name":"HJHDiscoverViewController","title":"消息","image":"tabbar_discover","vistor":["imageName":"visitordiscover_image_message","imageMsg":"登陆后，别人评论你的微博给你发送消息都会在这里看到"]
            ],
            
            ["name":""],
            
            ["name":"HJHMessageViewController","title":"发现","image":"tabbar_message_center","vistor":["imageName":"visitordiscover_image_message","imageMsg":"登陆后可看到最新微博和热门消息"]
            ],
            
            ["name":"HJHMineViewController","title":"我的","image":"tabbar_profile","vistor":["imageName":"visitordiscover_image_profile","imageMsg":"登陆后，你的个人信息都会展现在这里"]
            ]
        ]

       let jsonData =   try? JSONSerialization.data(withJSONObject: arr, options: .prettyPrinted)
        let url = NSURL(fileURLWithPath: "/Users/hejinhui/Desktop/json.plist")
        (jsonData as NSData?)?.write(to: url as URL, atomically: true)
         */
         var arrM = [UIViewController]()
        for dict in arr! {
            arrM.append(controller(dict: dict))
        }
        viewControllers = arrM
    }
    //使用字典创建一个子控制器
    private func controller(dict:[String:Any])->UIViewController
    {
        
        guard  let clsName = dict["name"] as? String,
            let title = dict["title"] as? String,
            let image = dict["image"] as? String,
            let cls  = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? HJHBaseViewController.Type,
        let visitor = dict["vistor"] as? [String: String] else {
                
                return UIViewController()
        }
        let vc = cls.init()
        vc.title = title
        vc.tabBarItem.image = UIImage(named: image)
        vc.tabBarItem.selectedImage = UIImage(named: image + "_selected")
        vc.visiteorDict = visitor
        let nav = HJHNavigationController(rootViewController: vc)
        return nav
    }
    
}
//方法一
extension HJHTabBarController{
        func setUpChildVc(){
        
        let homeVc = HJHHomeViewController()
        let discoverVc = HJHDiscoverViewController()
        let messageVc = HJHMessageViewController()
        let mineVc = HJHMineViewController()
        
        setUpChildVc(vc: homeVc, title: "首页", normalImage: "tabbar_home")
        setUpChildVc(vc: discoverVc, title: "发现", normalImage: "tabbar_discover")
        setUpChildVc(vc: messageVc, title: "消息", normalImage: "tabbar_message_center")
        setUpChildVc(vc: mineVc, title: "我的", normalImage: "tabbar_profile")
        setUpStyle()
    }
    /**
     添加子控制器
     */
    func setUpChildVc(vc:UIViewController,title:String,normalImage:String) {
        let selectImg = normalImage + "_selected"
        vc.title = title
        vc.tabBarItem.image = UIImage(named: normalImage)
        vc.tabBarItem.selectedImage = UIImage(named: selectImg)?.withRenderingMode(.alwaysOriginal)
        let nav = HJHNavigationController(rootViewController: vc)
        addChildViewController(nav)
    }
    
}

